import './attachmentUploader.scss';
/*eslint-disable */
import uploadResultContainerTpl from '!html-loader!./uploadResultContainer.html';
/*eslint-enable */

function attachmentUploaderComponent($compile, uiUploader, $log, $rootScope) {
  'ngInject';

  $rootScope.$removeFile = (file) => {
    uiUploader.removeFile(file);
    // if (file.createdTime || file.type) {
    //   $rootScope.$broadcast('remove-file', file);
    // }
    $rootScope.$broadcast('remove-file', file);
  };
  return {
    restrict: 'A',
    scope: {
      ngModel: '=',
      target: '@',
      url: '@',
      type: '@',
    },
    compile(tElement, tAttrs) {
      const fileInput = angular.element('<input class="invisible" type="file" name="file" id="file" multiple/>');
      if (tAttrs.type === 'image') {
        fileInput.attr('accept', 'image/*');
      }
      angular.element(document.body).append(fileInput);

      let targetSelector;
      let targetElement;
      let resultContainer;
      let ngModelStr;
      let compiled;
      if (tAttrs.target) {
        targetSelector = tAttrs.target;
        targetElement = angular.element(targetSelector);
        resultContainer = angular.element(uploadResultContainerTpl);
        ngModelStr = tAttrs.ngModel;

        resultContainer.find('.result-item').attr('ng-repeat', `file in ${ngModelStr} track by $index`);
        compiled = $compile(resultContainer);
      }

      return function link(scope, iElement, iAttrs) {
        if (compiled) {
          targetElement.append(compiled(scope.$parent));
        }

        const context = '/sgms';
        let url = scope.url || '/api/v1/common/uploadFile?folderName=common';
        url = context + url;
        tElement.click((e) => {
          if (e.target.tagName === 'INPUT') {
            e.stopPropagation();
          } else {
            fileInput.click();
          }
        });

        scope.$on('remove-file', (evt, file) => {
          const index = scope.ngModel.indexOf(file);
          if (index !== -1) {
            scope.ngModel.splice(index, 1);
          }
        });

        fileInput.change((e) => {
          const files = e.target.files;
          uiUploader.addFiles(files);
          // scope.ngModel = uiUploader.getFiles();
          // scope.ngModel.push(...files);
          scope.ngModel = scope.ngModel.concat(...files);
          scope.$apply();

          fileInput.val('');
          uiUploader.startUpload({
            url,
            concurrency: 2,
            onProgress(file) {
              if (!file.isUploading) {
                file.isUploading = true;
              }
              $log.info(`${file.name}=${file.humanSize}`);
              scope.$apply();
            },
            onCompleted(file, responseTxt) {
              const resp = JSON.parse(responseTxt);
              if (resp.success) {
                file.id = resp.data;
                file.success = true;
              } else {
                file.success = false;
              }
              file.isUploading = false;
              scope.$apply();
              $log.info(`${file} upload completed , ${responseTxt}`);
            },
          });
        });
      };
    },
  };
}

export default attachmentUploaderComponent;
